import { dom } from '@knno/dom';
import { toggleStyle } from './toggle.css';
import { Checkable } from '../checkbox/checkable';
import { groupStyle } from '../group/group.css';

export class Toggle extends Checkable {
	updateFacade(): void {
		// do nothing
	}
	constructor() {
		super(
			dom.button(toggleStyle).append(dom.div().append(dom.div())).attr({
				checked: 'false',
			})
		);
		this.on('click', () => {
			if (this.disabled()) return;
			const oldValue = this.checked();
			this.checked(!this.checked());
			if (oldValue != this.checked()) {
				this.emit(new Event('change'));
				if (this.parent().class().includes(groupStyle)) {
					this.parent().emit(new Event('change'));
				}
			}
		});
		this.on('update', (evt) => {
			this.checked(evt.detail.checked);
		});
	}

	checked(): boolean;
	checked(value: boolean): this;
	checked(value?: boolean): this | boolean {
		const currentValue = this.attr('checked') === 'true';
		if (value === undefined) {
			return currentValue;
		} else {
			if (currentValue !== value) {
				this.attr('checked', value ? 'true' : null);
			}
			return this;
		}
	}
}

export function toggle(...className: string[]): Toggle {
	return new Toggle().addClass(...className);
}
